diff --git a/objects/video_statistic.php b/objects/video_statistic.php index 3903e5d2b..55abb06a4 100644 --- a/objects/video_statistic.php +++ b/objects/video_statistic.php @@ -1,435 +1,464 @@ You need to update your system"; return false; } */ if (empty($videos_id)) { die(__("You need a video to generate statistics")); } $userId = empty($_SESSION["user"]["id"]) ? "NULL" : $_SESSION["user"]["id"]; $lastVideoTime = 0; if (empty($currentTime)) { $lastStatistic = self::getLastStatistics($videos_id, $userId); if (empty($currentTime) && !empty($lastStatistic)) { $lastVideoTime = intval($lastStatistic['lastVideoTime']); } } else { $lastVideoTime = intval($currentTime); } $sql = "INSERT INTO videos_statistics " . "(`when`,ip, users_id, videos_id, lastVideoTime, created, modified, session_id) values " . "(now(),?," . $userId . ",?,{$lastVideoTime},now(),now(),'" . session_id() . "')"; $insert_row = sqlDAL::writeSql($sql, "si", array(getRealIpAddr(), $videos_id)); if (!empty($global['mysqli']->insert_id)) { return $global['mysqli']->insert_id; } else { die($sql . ' Save Video Statistics Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } public static function updateStatistic($videos_id, $users_id, $lastVideoTime) { $lastStatistic = self::getLastStatistics($videos_id, $users_id); if (empty($lastStatistic)) { $vs = new VideoStatistic(0); $vs->setUsers_id($users_id); $vs->setVideos_id($videos_id); $vs->setWhen(date("Y-m-d h:i:s")); } else { $vs = new VideoStatistic($lastStatistic['id']); } $vs->setLastVideoTime($lastVideoTime); return $vs->save(); } public function save() { if (empty($this->videos_id)) { return false; } $this->setSession_id(session_id()); if (empty($this->session_id) && empty($this->users_id)) { return false; } if (empty($this->users_id)) { $this->setUsers_id('null'); } return parent::save(); } public static function getLastStatistics($videos_id, $users_id = 0) { if (!empty($users_id)) { $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND users_id = ? ORDER BY modified DESC LIMIT 1 "; $res = sqlDAL::readSql($sql, 'ii', array($videos_id, $users_id), true); } else { $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND session_id = ? ORDER BY modified DESC LIMIT 1 "; $res = sqlDAL::readSql($sql, 'is', array($videos_id, session_id()), true); } $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { return $result; } return false; } public static function getLastVideoTimeFromVideo($videos_id, $users_id) { $row = self::getLastStatistics($videos_id, $users_id); if (empty($row)) { return 0; } return intval($row['lastVideoTime']); } public static function getStatisticTotalViews($videos_id, $uniqueUsers = false, $startDate = "", $endDate = "") { global $global; if ($uniqueUsers) { $ast = "distinct(users_id)"; } else { $ast = "*"; } $sql = "SELECT count({$ast}) as total FROM videos_statistics WHERE 1=1 "; $formats = ""; $values = array(); if (!empty($videos_id)) { $sql .= " AND videos_id = ? "; $formats .= "i"; $values[] = $videos_id; } if (!empty($startDate)) { $sql .= " AND `when` >= ? "; $formats .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `when` <= ? "; $formats .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $formats, $values); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { //echo "
".$row['total']." --- ".$sql, "
"; return $result['total']; } return 0; } public static function getTotalLastDaysAsync($video_id, $numberOfDays) { global $global, $advancedCustom; $md5 = ("{$video_id}_{$numberOfDays}"); $path = getCacheDir() . "getTotalLastDaysAsync/"; make_path($path); $cacheFileName = "{$path}{$md5}"; if (!file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } $total = static::getTotalLastDays($video_id, $numberOfDays); file_put_contents($cacheFileName, json_encode($total)); return $total; } $return = _json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 60) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalLastDaysAsync.php' '$video_id' '$numberOfDays' '$cacheFileName'"); _error_log("getTotalLastDaysAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } public static function getTotalLastDays($video_id, $numberOfDays, $returnArray = array()) { if ($numberOfDays < 0) { return $returnArray; } $date = date("Y-m-d", strtotime("-{$numberOfDays} days")); $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . " 00:00:00", $date . " 23:59:59"); $numberOfDays--; return static::getTotalLastDays($video_id, $numberOfDays, $returnArray); } public static function getTotalToday($video_id, $hour = 0, $returnArray = array()) { if ($hour >= 24) { return $returnArray; } $date = date("Y-m-d {$hour}", time()); //echo $date;exit; $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . ":00:00", $date . ":59:59"); $hour++; return static::getTotalToday($video_id, $hour, $returnArray); } public static function getTotalTodayAsync($video_id) { global $global, $advancedCustom; $cacheFileName = getCacheDir() . "getTotalTodayAsync_{$video_id}"; if (!file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } $total = static::getTotalToday($video_id); file_put_contents($cacheFileName, json_encode($total)); return $total; } $return = _json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 60) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalTodayAsync.php' '$video_id' '$cacheFileName'"); _error_log("getTotalTodayAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } public function getWhen() { return $this->when; } public function getIp() { return $this->ip; } public function getUsers_id() { return $this->users_id; } public function getVideos_id() { return $this->videos_id; } public function getLastVideoTime() { return $this->lastVideoTime; } public function setWhen($when) { $this->when = $when; } public function setIp($ip) { $this->ip = $ip; } public function setUsers_id($users_id) { $this->users_id = intval($users_id); if (empty($this->users_id)) { $this->users_id = 'null'; } } public function setVideos_id($videos_id) { $this->videos_id = intval($videos_id); } public function setLastVideoTime($lastVideoTime) { $this->lastVideoTime = intval($lastVideoTime); } public function getSession_id() { return $this->session_id; } public function setSession_id($session_id) { $this->session_id = $session_id; } public static function getChannelsWithMoreViews($daysLimit = 30) { global $global; $cacheName3 = "getChannelsWithMoreViews{$daysLimit}" . DIRECTORY_SEPARATOR . md5(json_encode(array($_GET, $_POST))); $cache = ObjectYPT::getCache($cacheName3, 3600); // 1 hour cache if (!empty($cache)) { _error_log('getChannelsWithMoreViews cache found ' . $cacheName3); return object_to_array($cache); } else { _error_log('getChannelsWithMoreViews no cache found ' . $cacheName3); } // get unique videos ids from the requested timeframe $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE DATE(`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $channels = array(); $channelsPerUser = array(); $cacheName2 = "getChannelsWithMoreViews" . DIRECTORY_SEPARATOR . md5($sql); $cache2 = ObjectYPT::getCache($cacheName2, 3600); // 1 hour cache if (!empty($cache2)) { $channelsPerUser = object_to_array($cache2); } if (empty($channelsPerUser)) { $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { // get the channel owner from each of those videos foreach ($fullData as $row) { $users_id = Video::getOwner($row['videos_id']); if (empty($channelsPerUser[$users_id])) { $channelsPerUser[$users_id] = array(); } $channelsPerUser[$users_id][] = $row['videos_id']; } } $response = ObjectYPT::setCache($cacheName2, $channelsPerUser); } if (!empty($channelsPerUser)) { foreach ($channelsPerUser as $key => $value) { // count how many views each one has $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id IN (" . implode(",", $value) . ") AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); if (!empty($result2)) { $channels[$key]['users_id'] = $key; $channels[$key]['total'] = intval($result2['total']); } } // return more first usort($channels, function ($a, $b) { return $a['total'] - $b['total']; }); } $response = ObjectYPT::setCache($cacheName3, $channels); _error_log('getChannelsWithMoreViews cache saved [' . json_encode($response) . '] ' . $cacheName3); return $channels; } public static function getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly, $daysLimit = 30) { global $global; // get unique videos ids from the requested timeframe $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics s " . " LEFT JOIN videos v ON v.id = videos_id " . " WHERE DATE(s.`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $sql .= " AND v.users_id = '{$user['id']}' "; } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; } $sql .= static::getSqlLimit(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $channels = array(); $videos = array(); if ($res != false) { foreach ($fullData as $key => $value) { // count how many views each one has $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id = {$value['videos_id']} AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); if (!empty($result2)) { $video = Video::getVideo($value['videos_id'], $status, false, false, $suggestedOnly, $showUnlisted, false, $showOnlyLoggedUserVideos); if (empty($video)) { continue; } $video['total'] = $result2['total']; $videos[] = $video; } } } // return more first usort($videos, function ($a, $b) { return $a['total'] - $b['total']; }); return $videos; } public static function getUsersIDFromChannelsWithMoreViews($daysLimit = 30) { $channels = self::getChannelsWithMoreViews($daysLimit); $users_id = array(); foreach ($channels as $value) { $users_id[] = $value['users_id']; } return $users_id; } public static function getChannelsTotalViews($users_id, $daysLimit = 30) { global $global; $cacheName = "getChannelsTotalViews($users_id, $daysLimit)"; $cache = ObjectYPT::getCache($cacheName, 3600); // 1 hour cache if (!empty($cache)) { return object_to_array($cache); } $users_id = intval($users_id); // count how many views each one has $sql2 = "SELECT count(s.id) as total FROM videos_statistics s " . " LEFT JOIN videos v ON v.id = videos_id WHERE v.users_id = $users_id " . " AND DATE(s.`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); $result = 0; if (!empty($result2)) { $result = intval($result2['total']); } ObjectYPT::setCache($cacheName, $result); return 0; } + + + public static function getTotalStatisticsRecords() { + global $global; + $sql2 = "SELECT count(s.id) as total FROM videos_statistics s "; + $res2 = sqlDAL::readSql($sql2); + $result2 = sqlDAL::fetchAssoc($res2); + sqlDAL::close($res2); + $result = 0; + if (!empty($result2)) { + return intval($result2['total']); + } + ObjectYPT::setCache($cacheName, $result); + return 0; + } + + public static function deleteOldStatistics($days) { + global $global; + $days = intval($days); + if (!empty($days)) { + $sql = "DELETE FROM " . static::getTableName() . " "; + $sql .= " WHERE created < DATE_SUB(NOW(), INTERVAL ? DAY) "; + $global['lastQuery'] = $sql; + //_error_log("Delete Query: ".$sql); + return sqlDAL::writeSql($sql, "i", array($days)); + } + _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); + return false; + } } diff --git a/plugin/Cache/Cache.php b/plugin/Cache/Cache.php index ad0442423..e8480a6c7 100644 --- a/plugin/Cache/Cache.php +++ b/plugin/Cache/Cache.php @@ -1,283 +1,298 @@ Your website has 10,000 visitors who are online, and your dynamic page has to send 10,000 times the same queries to database on every page load. With this plugin, your page only sends 1 query to your DB, and uses the cache to serve the 9,999 other visitors."; $txt .= "
To auto delete the old cache files you can use this crontab command 0 2 * * * php {$global['systemRootPath']}plugin/Cache/crontab.php this will delete cache files that are 3 days old everyday at 2 AM"; $help = "
Help"; return $txt . $help; } public function getName() { return "Cache"; } public function getUUID() { return "10573225-3807-4167-ba81-0509dd280e06"; } public function getPluginVersion() { return "1.0"; } public function getEmptyDataObject() { global $global; $obj = new stdClass(); $obj->enableCachePerUser = false; $obj->enableCacheForLoggedUsers = false; $obj->cacheTimeInSeconds = 600; $obj->cacheDir = $global['systemRootPath'] . 'videos/cache/'; $obj->logPageLoadTime = false; $obj->stopBotsFromNonCachedPages = false; + $obj->deleteStatisticsDaysOld = 180; // 6 months return $obj; } public function getCacheDir($ignoreFirstPage = true) { global $global; $obj = $this->getDataObject(); if (!$ignoreFirstPage && $this->isFirstPage()) { $obj->cacheDir .= "firstPage".DIRECTORY_SEPARATOR; } if (User::isLogged()) { if(User::isAdmin()){ $obj->cacheDir .= 'admin_'.md5("admin".$global['salt']).DIRECTORY_SEPARATOR; }else{ $obj->cacheDir .= 'user_'.md5("user".$global['salt']).DIRECTORY_SEPARATOR; } }else{ $obj->cacheDir .= 'notlogged_'.md5("notlogged".$global['salt']).DIRECTORY_SEPARATOR; } $obj->cacheDir = fixPath($obj->cacheDir, true); if (!file_exists($obj->cacheDir)) { $obj->cacheDir = $global['systemRootPath'] . 'videos'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR; $this->setDataObject($obj); if (!file_exists($obj->cacheDir)) { mkdir($obj->cacheDir, 0777, true); } } return $obj->cacheDir; } private function getFileName() { if (empty($_SERVER['REQUEST_URI'])) { $_SERVER['REQUEST_URI'] = ""; } $obj = $this->getDataObject(); $session_id = ""; if (!empty($obj->enableCachePerUser)) { $session_id = session_id(); } $compl = ""; if (!empty($_SERVER['HTTP_USER_AGENT']) && get_browser_name($_SERVER['HTTP_USER_AGENT']) === 'Safari') { $compl .= "safari_"; } $dir = ""; $plugin = AVideoPlugin::loadPluginIfEnabled('User_Location'); if (!empty($plugin)) { $location = User_Location::getThisUserLocation(); if (!empty($location['country_code'])) { $dir = $location['country_code'] . "/"; } } return $dir . User::getId() . "_{$compl}" . md5(@$_SESSION['channelName'] . $_SERVER['REQUEST_URI'] . $_SERVER['HTTP_HOST']) . "_" . $session_id . "_" . (!empty($_SERVER['HTTPS']) ? 'a' : '') . (@$_SESSION['language']) . '.cache'; } private function isFirstPage() { return isFirstPage(); } public function getStart() { global $global; // ignore cache if it is command line //var_dump($this->isFirstPage());exit; $obj = $this->getDataObject(); if ($obj->logPageLoadTime) { $this->start(); } if (isCommandLineInterface()) { return true; } $whitelistedFiles = array('user.php', 'status.php', 'canWatchVideo.json.php', '/login', '/status'); $blacklistedFiles = array('videosAndroid.json.php'); $baseName = basename($_SERVER["SCRIPT_FILENAME"]); if (isVideo() || isLive() || isLiveLink() || in_array($baseName, $whitelistedFiles) || in_array($_SERVER['REQUEST_URI'], $whitelistedFiles)) { return true; } $isBot = isBot(); if ($this->isBlacklisted() || $this->isFirstPage() || !class_exists('User') || !User::isLogged() || !empty($obj->enableCacheForLoggedUsers)) { $cacheName = 'firstPage'.DIRECTORY_SEPARATOR.$this->getFileName(); $lifetime = $obj->cacheTimeInSeconds; if($isBot && $lifetime < 3600){ $lifetime = 3600; } $firstPageCache = ObjectYPT::getCache($cacheName, $lifetime, true); if(!empty($firstPageCache) && strtolower($firstPageCache) != 'false'){ if ($isBot && $_SERVER['REQUEST_URI'] !== '/login') { //_error_log("Bot Detected, showing the cache ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}"); } //$c = @local_get_contents($cachefile); if (preg_match("/\.json\.?/", $baseName)) { header('Content-Type: application/json'); } if($isBot){ $firstPageCache = strip_specific_tags($firstPageCache); $firstPageCache = strip_render_blocking_resources($firstPageCache); }else{ $firstPageCache = optimizeHTMLTags($firstPageCache); } echo $firstPageCache.PHP_EOL.''; if ($obj->logPageLoadTime) { $this->end("Cache"); } exit; } } if ($isBot && !self::isREQUEST_URIWhitelisted() && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') { if (empty($_SERVER['HTTP_USER_AGENT'])) { $_SERVER['HTTP_USER_AGENT'] = ""; } _error_log("Bot Detected, NOT showing the cache ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}"); if ($obj->stopBotsFromNonCachedPages) { _error_log("Bot stopped"); exit; } } //ob_start('sanitize_output'); ob_start(); } public function getEnd() { global $global; $obj = $this->getDataObject(); echo PHP_EOL.''; $c = ob_get_clean(); $c = optimizeHTMLTags($c); ob_start(); echo $c; if (!headers_sent()) { header_remove('Set-Cookie'); } /* if (!file_exists($this->getCacheDir())) { mkdir($this->getCacheDir(), 0777, true); } * */ if ($this->isBlacklisted() || $this->isFirstPage() || !class_exists('User') || !User::isLogged() || !empty($obj->enableCacheForLoggedUsers)) { $cacheName = 'firstPage'.DIRECTORY_SEPARATOR.$this->getFileName(); $r = ObjectYPT::setCache($cacheName, $c); //var_dump($r); } if ($obj->logPageLoadTime) { $this->end(); } } private function isREQUEST_URIWhitelisted() { $cacheBotWhitelist = array( 'aVideoEncoder', 'plugin/Live/on_', 'plugin/YPTStorage', '/login', 'restreamer.json.php', 'plugin/API', '/info?version=', 'Meet', '/roku.json', 'mrss', '/sitemap.xml', 'plugin/Live/verifyToken.json.php'); foreach ($cacheBotWhitelist as $value) { if (strpos($_SERVER['REQUEST_URI'], $value) !== false) { _error_log("Cache::isREQUEST_URIWhitelisted: ($value) is whitelisted"); return true; } } return false; } private function isBlacklisted() { $blacklistedFiles = array('videosAndroid.json.php'); $baseName = basename($_SERVER["SCRIPT_FILENAME"]); return in_array($baseName, $blacklistedFiles); } private function start() { global $global; $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $global['cachePluginStart'] = $time; } private function end($type = "No Cache") { global $global; if (empty($global['cachePluginStart'])) { return false; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; if (User::isLogged()) { $type = "User: " . User::getUserName() . " - " . $type; } else { $type = "User: Not Logged - " . $type; } $t = (floatval($finish) - floatval($global['cachePluginStart'])); $total_time = round($t, 4); _error_log("Page generated in {$total_time} seconds. {$type} ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}"); } + + public function getPluginMenu() { + global $global; + $fileAPIName = $global['systemRootPath'] . 'plugin/Cache/pluginMenu.html'; + $content = file_get_contents($fileAPIName); + return $content; + } + + public function getFooterCode() { + global $global; + if(preg_match('/managerPlugins.php$/', $_SERVER["SCRIPT_FILENAME"])){ + return ""; + } + } } function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', // strip whitespaces after tags, except space '/[^\S ]+\/' // Remove HTML comments ); $replace = array( '>', '<', '\\1', '' ); $len = strlen($buffer); if ($len) { _error_log("Before Sanitize: " . strlen($buffer)); $buffer = preg_replace($search, $replace, $buffer); $lenAfter = strlen($buffer); _error_log("After Sanitize: {$lenAfter} = " . (($len / $lenAfter) * 100) . "%"); } return $buffer; } diff --git a/plugin/Cache/deleteStatistics.json.php b/plugin/Cache/deleteStatistics.json.php new file mode 100644 index 000000000..1d3bf7e29 --- /dev/null +++ b/plugin/Cache/deleteStatistics.json.php @@ -0,0 +1,31 @@ +error = true; +$obj->msg = ""; +$obj->result = ""; + +if (!User::isAdmin()) { + $obj->msg = "You cant do this"; + die(json_encode($obj)); +} + +require_once $global['systemRootPath'] . 'objects/video_statistic.php'; + +$objC = AVideoPlugin::getDataObject('Cache'); + +$days = $objC->deleteStatisticsDaysOld; +if(empty($days)){ + $days = 180; +} +$obj->before = VideoStatistic::getTotalStatisticsRecords(); +$obj->result = VideoStatistic::deleteOldStatistics($days); +$obj->after = VideoStatistic::getTotalStatisticsRecords(); +$obj->error = empty($obj->result); + +$obj->msg = "you had ". number_format($obj->before, 0)." statistics records and removed ". number_format($obj->before-$obj->after, 0)." now you have ". number_format($obj->after, 0); + +echo json_encode($obj); diff --git a/plugin/Cache/pluginMenu.html b/plugin/Cache/pluginMenu.html new file mode 100644 index 000000000..baea2493d --- /dev/null +++ b/plugin/Cache/pluginMenu.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/plugin/Cache/pluginMenu.js b/plugin/Cache/pluginMenu.js new file mode 100644 index 000000000..ce3a8267d --- /dev/null +++ b/plugin/Cache/pluginMenu.js @@ -0,0 +1,10 @@ +function deleteOldStatistics() { + modal.showPleaseWait(); + $.ajax({ + url: webSiteRootURL + 'plugin/Cache/deleteStatistics.json.php', + success: function (response) { + avideoResponse(response); + modal.hidePleaseWait(); + } + }); +} \ No newline at end of file diff --git a/view/js/script.js b/view/js/script.js index 84f0f6543..e1f0edb6a 100644 --- a/view/js/script.js +++ b/view/js/script.js @@ -1,1725 +1,1739 @@ var modal; var player; var floatLeft = ""; var floatTop = ""; var floatWidth = ""; var floatHeight = ""; var changingVideoFloat = 0; var floatClosed = 0; var fullDuration = 0; var isPlayingAd = false; var mainVideoHeight = 0; var mouseX; var mouseY; var videoContainerDragged = false; var youTubeMenuIsOpened = false; var userIsControling = false; var _serverTime; var _serverDBTime; var _serverTimeString; var _serverDBTimeString; let deferredPrompt; $(document).mousemove(function (e) { mouseX = e.pageX; mouseY = e.pageY; }); String.prototype.stripAccents = function () { var returnvar = this.replace(/[áàâãªä]/g, 'a'); returnvar = returnvar.replace(/[ÁÀÂÃÄ]/g, 'A'); returnvar = returnvar.replace(/[ÍÌÎÏ]/g, 'I'); returnvar = returnvar.replace(/[íìîï]/g, 'i'); returnvar = returnvar.replace(/[éèêë]/g, 'e'); returnvar = returnvar.replace(/[ÉÈÊË]/g, 'E'); returnvar = returnvar.replace(/[óòôõºö]/g, 'o'); returnvar = returnvar.replace(/[ÓÒÔÕÖ]/g, 'O'); returnvar = returnvar.replace(/[úùûü]/g, 'u'); returnvar = returnvar.replace(/[ÚÙÛÜ]/g, 'U'); returnvar = returnvar.replace(/ç/g, 'c'); returnvar = returnvar.replace(/Ç/g, 'C'); returnvar = returnvar.replace(/ñ/g, 'n'); returnvar = returnvar.replace(/Ñ/g, 'N'); returnvar = returnvar.replace(/–/g, '-'); returnvar = returnvar.replace(/[’‘‹›‚]/g, ' '); returnvar = returnvar.replace(/[“”«»„]/g, ' '); returnvar = returnvar.replace(/ /g, ' '); returnvar = returnvar.replace(/Є/g, 'YE'); returnvar = returnvar.replace(/І/g, 'I'); returnvar = returnvar.replace(/Ѓ/g, 'G'); returnvar = returnvar.replace(/і/g, 'i'); returnvar = returnvar.replace(/№/g, '#'); returnvar = returnvar.replace(/є/g, 'ye'); returnvar = returnvar.replace(/ѓ/g, 'g'); returnvar = returnvar.replace(/А/g, 'A'); returnvar = returnvar.replace(/Б/g, 'B'); returnvar = returnvar.replace(/В/g, 'V'); returnvar = returnvar.replace(/Г/g, 'G'); returnvar = returnvar.replace(/Д/g, 'D'); returnvar = returnvar.replace(/Е/g, 'E'); returnvar = returnvar.replace(/Ё/g, 'YO'); returnvar = returnvar.replace(/Ж/g, 'ZH'); returnvar = returnvar.replace(/З/g, 'Z'); returnvar = returnvar.replace(/И/g, 'I'); returnvar = returnvar.replace(/Й/g, 'J'); returnvar = returnvar.replace(/К/g, 'K'); returnvar = returnvar.replace(/Л/g, 'L'); returnvar = returnvar.replace(/М/g, 'M'); returnvar = returnvar.replace(/Н/g, 'N'); returnvar = returnvar.replace(/О/g, 'O'); returnvar = returnvar.replace(/П/g, 'P'); returnvar = returnvar.replace(/Р/g, 'R'); returnvar = returnvar.replace(/С/g, 'S'); returnvar = returnvar.replace(/Т/g, 'T'); returnvar = returnvar.replace(/У/g, 'U'); returnvar = returnvar.replace(/Ф/g, 'F'); returnvar = returnvar.replace(/Х/g, 'H'); returnvar = returnvar.replace(/Ц/g, 'C'); returnvar = returnvar.replace(/Ч/g, 'CH'); returnvar = returnvar.replace(/Ш/g, 'SH'); returnvar = returnvar.replace(/Щ/g, 'SHH'); returnvar = returnvar.replace(/Ъ/g, ''); returnvar = returnvar.replace(/Ы/g, 'Y'); returnvar = returnvar.replace(/Ь/g, ''); returnvar = returnvar.replace(/Э/g, 'E'); returnvar = returnvar.replace(/Ю/g, 'YU'); returnvar = returnvar.replace(/Я/g, 'YA'); returnvar = returnvar.replace(/а/g, 'a'); returnvar = returnvar.replace(/б/g, 'b'); returnvar = returnvar.replace(/в/g, 'v'); returnvar = returnvar.replace(/г/g, 'g'); returnvar = returnvar.replace(/д/g, 'd'); returnvar = returnvar.replace(/е/g, 'e'); returnvar = returnvar.replace(/ё/g, 'yo'); returnvar = returnvar.replace(/ж/g, 'zh'); returnvar = returnvar.replace(/з/g, 'z'); returnvar = returnvar.replace(/и/g, 'i'); returnvar = returnvar.replace(/й/g, 'j'); returnvar = returnvar.replace(/к/g, 'k'); returnvar = returnvar.replace(/л/g, 'l'); returnvar = returnvar.replace(/м/g, 'm'); returnvar = returnvar.replace(/н/g, 'n'); returnvar = returnvar.replace(/о/g, 'o'); returnvar = returnvar.replace(/п/g, 'p'); returnvar = returnvar.replace(/р/g, 'r'); returnvar = returnvar.replace(/с/g, 's'); returnvar = returnvar.replace(/т/g, 't'); returnvar = returnvar.replace(/у/g, 'u'); returnvar = returnvar.replace(/ф/g, 'f'); returnvar = returnvar.replace(/х/g, 'h'); returnvar = returnvar.replace(/ц/g, 'c'); returnvar = returnvar.replace(/ч/g, 'ch'); returnvar = returnvar.replace(/ш/g, 'sh'); returnvar = returnvar.replace(/щ/g, 'shh'); returnvar = returnvar.replace(/ъ/g, ''); returnvar = returnvar.replace(/ы/g, 'y'); returnvar = returnvar.replace(/ь/g, ''); returnvar = returnvar.replace(/э/g, 'e'); returnvar = returnvar.replace(/ю/g, 'yu'); returnvar = returnvar.replace(/я/g, 'ya'); returnvar = returnvar.replace(/—/g, '-'); returnvar = returnvar.replace(/«/g, ''); returnvar = returnvar.replace(/»/g, ''); returnvar = returnvar.replace(/…/g, ''); return returnvar; }; function clean_name(str) { str = str.stripAccents().toLowerCase(); return str.replace(/[!#$&'()*+,/:;=?@[\] ]+/g, "-"); } function lazyImage() { try { if ($(".thumbsJPG").length) { $('.thumbsJPG').lazy({ effect: 'fadeIn', visibleOnly: true, // called after an element was successfully handled afterLoad: function (element) { element.addClass('gifNotLoaded'); element.removeClass('blur'); element.mouseover(function () { if ($(this).hasClass('gifNotLoaded')) { var element = $(this); element.removeClass('gifNotLoaded'); var gif = element.parent().find('.thumbsGIF'); gif.lazy({ effect: 'fadeIn' }); gif.height(element.height()); gif.width(element.width()); //console.log('lazyImage', gif); } $("#log").append("
Handler for .mouseover() called.
"); }); } }); mouseEffect(); } } catch (e) { } } lazyImage(); var pleaseWaitIsINUse = false; var pauseIfIsPlayinAdsInterval; function setPlayerListners() { if (typeof player !== 'undefined') { player.on('pause', function () { clearTimeout(promisePlayTimeout); console.log("setPlayerListners: pause"); //userIsControling = true; clearInterval(pauseIfIsPlayinAdsInterval); }); player.on('play', function () { isTryingToPlay = false; clearTimeout(promisePlayTimeout); console.log("setPlayerListners: play"); //userIsControling = true; pauseIfIsPlayinAdsInterval = setInterval(function () { pauseIfIsPlayinAds(); }, 500); }); $("#mainVideo .vjs-mute-control").click(function () { Cookies.set('muted', player.muted(), { path: '/', expires: 365 }); }); } else { setTimeout(function () { setPlayerListners(); }, 2000); } } function removeTracks() { var oldTracks = player.remoteTextTracks(); var i = oldTracks.length; while (i--) { player.removeRemoteTextTrack(oldTracks[i]); } } function changeVideoSrc(vid_obj, source) { var srcs = []; removeTracks(); for (i = 0; i < source.length; i++) { if (source[i].type) { console.log(source[i].type); if (source[i].type === "application/x-mpegURL") { // it is HLS cancel it return false; } srcs.push(source[i]); } else if (source[i].srclang) { player.addRemoteTextTrack(source[i]); } } vid_obj.src(srcs); setTimeout(function () { changeVideoSrcLoad(); }, 1000); return true; } function changeVideoSrcLoad() { console.log("changeVideoSrcLoad: Try to load player"); player.load(); player.ready(function () { console.log("changeVideoSrcLoad: Player ready"); var err = this.error(); if (err && err.code) { console.log("changeVideoSrcLoad: Load player Error"); setTimeout(function () { changeVideoSrcLoad(); }, 1000); } else { console.log("changeVideoSrcLoad: Load player Success, Play"); setTimeout(function () { player.load(); console.log("changeVideoSrcLoad: Trying to play"); player.play(); }, 1000); } }); } var _reloadAdsTimeout; var isReloadingAds = false; function reloadAds() { if (isReloadingAds) { return false; } isReloadingAds = true; setTimeout(function () { isReloadingAds = false; }, 500); clearTimeout(_reloadAdsTimeout); console.log('reloadAds '); if (playerIsReady() && player.ima) { try { console.log('reloadAds player.ima.getAdsManager()', player.ima.getAdsManager()); if (player.ima.getAdsManager()) { player.ima.requestAds(); } player.ima.changeAdTag(null); player.ima.setContentWithAdTag(null, _adTagUrl, false); player.ima.changeAdTag(_adTagUrl); setTimeout(function () { player.ima.requestAds(); console.log('reloadAds done'); }, 2000); player.ima.requestAds(); } catch (e) { console.log('reloadAds ERROR', e.message); } } else { _reloadAdsTimeout = setTimeout(function () { reloadAds(); }, 200); } } /** * * @param {String} str 00:00:00 * @returns {int} int of seconds */ function strToSeconds(str) { var partsOfStr = str.split(':'); var seconds = parseInt(partsOfStr[2]); seconds += parseInt(partsOfStr[1]) * 60; seconds += parseInt(partsOfStr[0]) * 60 * 60; return seconds; } /** * * @param {int} seconds * @param {int} level 3 = 00:00:00 2 = 00:00 1 = 00 * @returns {String} 00:00:00 */ function secondsToStr(seconds, level) { var hours = parseInt(seconds / (60 * 60)); var minutes = parseInt(seconds / (60)); seconds = parseInt(seconds % (60)); hours = hours > 9 ? hours : "0" + hours; minutes = minutes > 9 ? minutes : "0" + minutes; seconds = seconds > 9 ? seconds : "0" + seconds; switch (level) { case 3: return hours + ":" + minutes + ":" + seconds; break; case 2: return minutes + ":" + seconds; break; case 1: return seconds; break; default: return hours + ":" + minutes + ":" + seconds; } } function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function isEmailValid(email) { return validateEmail(email); } function subscribe(email, user_id) { $.ajax({ url: webSiteRootURL + 'objects/subscribe.json.php', method: 'POST', data: { 'email': email, 'user_id': user_id }, success: function (response) { if (response.subscribe == "i") { $('.subs' + user_id).removeClass("subscribed"); $('.subs' + user_id + ' b.text').text("Subscribe"); $('b.textTotal' + user_id).text(parseInt($('b.textTotal' + user_id).first().text()) - 1); } else { $('.subs' + user_id).addClass("subscribed"); $('.subs' + user_id + ' b.text').text("Subscribed"); $('b.textTotal' + user_id).text(parseInt($('b.textTotal' + user_id).first().text()) + 1); } $('#popover-content #subscribeEmail').val(email); $('.subscribeButton' + user_id).popover('hide'); } }); } function subscribeNotify(email, user_id) { $.ajax({ url: webSiteRootURL + 'objects/subscribeNotify.json.php', method: 'POST', data: { 'email': email, 'user_id': user_id }, success: function (response) { if (response.notify) { $('.notNotify' + user_id).addClass("hidden"); $('.notify' + user_id).removeClass("hidden"); } else { $('.notNotify' + user_id).removeClass("hidden"); $('.notify' + user_id).addClass("hidden"); } } }); } function mouseEffect() { $(".thumbsImage").on("mouseenter", function () { var gif = $(this).find(".thumbsGIF"); var jpg = $(this).find(".thumbsJPG"); try { gif.lazy({effect: 'fadeIn'}); setTimeout(function () { gif.height(jpg.height()); gif.width(jpg.width()); }, 100); } catch (e) { } gif.height(jpg.height()); gif.width(jpg.width()); gif.stop(true, true).fadeIn(); }); $(".thumbsImage").on("mouseleave", function () { $(this).find(".thumbsGIF").stop(true, true).fadeOut(); }); } function isMobile() { var check = false; (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true })(navigator.userAgent || navigator.vendor || window.opera); return check; } var last_videos_id = 0; var last_currentTime = -1; function addView(videos_id, currentTime) { if (last_videos_id == videos_id && last_currentTime == currentTime) { return false; } if (currentTime > 5 && currentTime % 30 !== 0) { // only update each 30 seconds return false; } last_videos_id = videos_id; last_currentTime = currentTime; _addView(videos_id, currentTime); } function _addView(videos_id, currentTime) { $.ajax({ url: webSiteRootURL + 'objects/videoAddViewCount.json.php', method: 'POST', data: { 'id': videos_id, 'currentTime': currentTime }, success: function (response) { $('.view-count' + videos_id).text(response.count); } }); } function getPlayerButtonIndex(name) { var children = player.getChild('controlBar').children(); for (i = 0; i < children.length; i++) { if (children[i].name_ === name) { return i; } } return children.length; } function copyToClipboard(text) { $('body').append(''); $('#elementToCopyAvideo').css({'top': mouseY, 'left': 0}).fadeIn('slow'); $('#elementToCopyAvideo').val(text); $('#elementToCopyAvideo').focus(); $('#elementToCopyAvideo').select(); document.execCommand('copy'); $('#elementToCopyAvideo').remove(); $.toast("Copied to Clipboard"); } function nl2br(str, is_xhtml) { if (typeof str === 'undefined' || str === null) { return ''; } var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '
' : '
'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); } function inIframe() { try { return window.self !== window.top; } catch (e) { return true; } } function playerIsReady() { return (typeof player !== 'undefined' && player.isReady_); } var promisePlaytry = 20; var promisePlayTimeoutTime = 500; var promisePlayTimeout; var promisePlay; var browserPreventShowed = false; var playerPlayTimeout; var isTryingToPlay = false; function playerPlay(currentTime) { isTryingToPlay = true; clearTimeout(playerPlayTimeout); if (playerIsPlayingAds()) { return false; } if (currentTime) { console.log("playerPlay time:", currentTime); } if (!playerIsReady()) { playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); return false; } if (userIsControling) { // stops here if the user already clicked on play or pause console.log("playerPlay: userIsControling"); return true; } if (promisePlaytry <= 0) { console.log("playerPlay: promisePlaytry <= 0"); if (!browserPreventShowed) { browserPreventShowed = true; $.toast("Your browser prevent autoplay"); } return false; } promisePlaytry--; if (typeof player !== 'undefined') { if (currentTime) { setCurrentTime(currentTime); } try { console.log("playerPlay: Trying to play", player); promisePlay = player.play(); if (promisePlay !== undefined) { tryToPlay(currentTime); console.log("playerPlay: promise found", currentTime); promisePlay.then(function () { console.log("playerPlay: Autoplay started", currentTime); userIsControling = true; if (player.paused()) { console.log("The video still paused, trying to mute and play"); if (promisePlaytry <= 10) { console.log("playerPlay: (" + promisePlaytry + ") The video still paused, trying to mute and play"); tryToPlayMuted(currentTime); } else { console.log("playerPlay: (" + promisePlaytry + ") The video still paused, trying to play again"); tryToPlay(currentTime); } } else { //player.muted(false); if (player.muted() && !inIframe()) { showUnmutePopup(); } } }).catch(function (error) { if (player.networkState() === 3) { promisePlaytry = 20; console.log("playerPlay: Network error detected, trying again"); player.src(player.currentSources()); userIsControling = false; tryToPlay(currentTime); } else { if (promisePlaytry <= 10) { console.log("playerPlay: (" + promisePlaytry + ") Autoplay was prevented, trying to mute and play ***"); tryToPlayMuted(currentTime); } else { console.log("playerPlay: (" + promisePlaytry + ") Autoplay was prevented, trying to play again"); tryToPlay(currentTime); } } }); } else { tryToPlay(currentTime); } } catch (e) { console.log("playerPlay: We could not autoplay, trying again in 1 second"); tryToPlay(currentTime); } } else { console.log("playerPlay: Player is Undefined"); } } function showUnmutePopup() { var donotShowUnmuteAgain = Cookies.get('donotShowUnmuteAgain'); if (!donotShowUnmuteAgain) { var span = document.createElement("span"); span.innerHTML = "Would you like to unmute it?
"; swal({ title: "Your Media is Muted", icon: "warning", content: span, dangerMode: true, buttons: { cancel: "Cancel", unmute: true, donotShowUnmuteAgain: { text: "Don't show again", value: "donotShowUnmuteAgain", className: "btn-danger", }, } }).then(function (value) { switch (value) { case "unmute": player.muted(false); break; case "donotShowUnmuteAgain": Cookies.set('donotShowUnmuteAgain', true, { path: '/', expires: 365 }); break; } }); } showMuteTooltip(); setTimeout(function () { $("#allowAutoplay").load(webSiteRootURL + "plugin/PlayerSkins/allowAutoplay/"); player.userActive(true); }, 500); } function tryToPlay(currentTime) { clearTimeout(promisePlayTimeout); promisePlayTimeout = setTimeout(function () { if (player.paused()) { playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } }, promisePlayTimeoutTime); } function tryToPlayMuted(currentTime) { muteInCookieAllow(); return tryToPlay(currentTime); } function muteIfNotAudio() { if (!player.isAudio()) { console.log("muteIfNotAudio: We will mute this video"); player.muted(true); return true; } console.log("muteIfNotAudio: We will not mute an audio"); return false; } function muteInCookieAllow() { var mute = Cookies.get('muted'); if (isALiveContent() || typeof mute === 'undefined' || (mute && mute !== "false")) { console.log("muteInCookieAllow: said yes"); return muteIfNotAudio(); } console.log("muteInCookieAllow: said no"); return false; } function playMuted(currentTime) { muteInCookieAllow(); playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } function showMuteTooltip() { if ($("#mainVideo .vjs-volume-panel").length) { if (!$("#mainVideo .vjs-volume-panel").is(":visible")) { setTimeout(function () { showMuteTooltip(); }, 500); return false; } $("#mainVideo .vjs-volume-panel").attr("data-toggle", "tooltip"); $("#mainVideo .vjs-volume-panel").attr("data-placement", "top"); $("#mainVideo .vjs-volume-panel").attr("title", "Click to activate the sound"); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip({container: '.vjs-control-bar'}); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('show'); $("#mainVideo .vjs-volume-panel").click(function () { console.log("remove unmute tooltip"); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('hide'); $("#mainVideo .vjs-volume-panel").removeAttr("data-toggle"); $("#mainVideo .vjs-volume-panel").removeAttr("data-placement"); $("#mainVideo .vjs-volume-panel").removeAttr("title"); $("#mainVideo .vjs-volume-panel").removeData('tooltip').unbind().next('div.tooltip').remove(); }); } player.userActive(true); setTimeout(function () { player.userActive(true); }, 1000); setTimeout(function () { player.userActive(true); }, 1500); setTimeout(function () { $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('hide'); }, 5000); } function playerPlayIfAutoPlay(currentTime) { if(isWebRTC()){ return false; } if (isAutoplayEnabled()) { playerPlayTimeout = setTimeout(function () { console.log('playerPlayIfAutoPlay true', currentTime); playerPlay(currentTime); }, 200); return true; } console.log('playerPlayIfAutoPlay false', currentTime); if (currentTime) { setCurrentTime(currentTime); } //$.toast("Autoplay disabled"); return false; } function playNext(url) { if (!player.paused()) { return false; } if (playerIsPlayingAds()) { setTimeout(function () { playNext(url); }, 1000); } else if (isPlayNextEnabled()) { modal.showPleaseWait(); if (typeof autoPlayAjax == 'undefined' || !autoPlayAjax) { console.log("playNext changing location " + url); document.location = url; } else { console.log("playNext ajax"); $.ajax({ url: webSiteRootURL + 'view/infoFromURL.php?url=' + encodeURI(url), success: function (response) { console.log(response); if (!response || response.error) { console.log("playNext ajax fail"); if (response.url) { //document.location = response.url; } } else { console.log("playNext ajax success"); $('topInfo').hide(); playNextURL = (typeof isEmbed !== 'undefined' && isEmbed) ? response.nextURLEmbed : response.nextURL; console.log("New playNextURL", playNextURL); var cSource = false; try { cSource = changeVideoSrc(player, response.sources); } catch (e) { console.log('changeVideoSrc', e.message); } if (!cSource) { document.location = url; return false; } $('video, #mainVideo').attr('poster', response.poster); history.pushState(null, null, url); $('.topInfoTitle, title').text(response.title); $('#topInfo img').attr('src', response.userPhoto); $('#topInfo a').attr('href', response.url); modal.hidePleaseWait(); if ($('#modeYoutubeBottom').length) { $.ajax({ url: url, success: function (response) { modeYoutubeBottom = $(response).find('#modeYoutubeBottom').html(); $('#modeYoutubeBottom').html(modeYoutubeBottom); } }); } } } }); } } else if (isPlayerLoop()) { avideoToast("Looping video"); userIsControling = false; playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } } function formatBytes(bytes, decimals) { if (bytes == 0) return '0 Bytes'; var k = 1024, dm = decimals <= 0 ? 0 : decimals || 2, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } function tooglePlayerLoop() { setPlayerLoop(!isPlayerLoop()); } var setPlayerLoopSetTimeout; function setPlayerLoop(loop) { clearTimeout(setPlayerLoopSetTimeout); if (typeof player === 'undefined') { setPlayerLoopSetTimeout = setTimeout(function () { setPlayerLoop(loop) }, 1000); return false; } if (loop) { console.log("Loop ON"); //$.toast("Loop ON"); player.loop(1); $(".loop-button").removeClass('loop-disabled-button'); $(".loop-button, .loopButton").addClass('fa-spin'); } else { $(".loop-button").addClass('loop-disabled-button'); $(".loop-button, .loopButton").removeClass('fa-spin'); console.log("Loop OFF"); //$.toast("Loop OFF"); player.loop(0); } Cookies.set('playerLoop', loop, { path: '/', expires: 365 }); if (typeof setImageLoop === 'function') { setImageLoop(); } } function setImageLoop() { if (isPlayerLoop()) { $('.loopButton').removeClass('opacityBtn'); $('.loopButton').addClass('fa-spin'); } else { $('.loopButton').addClass('opacityBtn'); $('.loopButton').removeClass('fa-spin'); } } function toogleImageLoop(t) { tooglePlayerLoop(); if (typeof setImageLoop === 'function') { setImageLoop(); } } function isPlayerLoop() { if (typeof player === 'undefined') { return false; } var loop = Cookies.get('playerLoop'); if (!loop || loop === "false") { return player.loop(); } else { return true; } } function isArray(what) { return Object.prototype.toString.call(what) === '[object Array]'; } function reloadVideoJS() { if (typeof player.currentSources === 'function') { var src = player.currentSources(); player.src(src); } } var initdone = false; function setCurrentTime(currentTime) { console.log('setCurrentTime', currentTime); if (typeof player !== 'undefined') { if (isTryingToPlay) { if (currentTime <= player.currentTime()) { console.log('setCurrentTime is trying to play', currentTime); return false; // if is trying to play, only update if the time is greater } } player.currentTime(currentTime); initdone = false; // wait for video metadata to load, then set time player.on("loadedmetadata", function () { player.currentTime(currentTime); }); // iPhone/iPad need to play first, then set the time // events: https://www.w3.org/TR/html5/embedded-content-0.html#mediaevents player.on("canplaythrough", function () { if (!initdone) { player.currentTime(currentTime); initdone = true; } }); } else { setTimeout(function () { setCurrentTime(currentTime); }, 1000); } } function isALiveContent() { if (typeof isLive !== 'undefined' && isLive && (typeof isOnlineLabel === 'undefined' || isOnlineLabel === true)) { return true; } return false; } function isWebRTC() { if (typeof isWebRTC !== 'undefined') { return isWebRTC; } return false; } function isAutoplayEnabled() { //console.log("Cookies.get('autoplay')", Cookies.get('autoplay')); if (isWebRTC()) { return false; } else if (isALiveContent()) { //console.log("isAutoplayEnabled always autoplay live contents"); return true; } else if ($("#autoplay").length && $("#autoplay").is(':visible')) { autoplay = $("#autoplay").is(":checked"); //console.log("isAutoplayEnabled #autoplay said " + ((autoplay) ? "Yes" : "No")); setAutoplay(autoplay); return autoplay; } else if ( typeof Cookies !== 'undefined' && typeof Cookies.get('autoplay') !== 'undefined' ) { if (Cookies.get('autoplay') === 'true' || Cookies.get('autoplay') == true) { //console.log("isAutoplayEnabled Cookie said Yes "); setAutoplay(true); return true; } else { //console.log("isAutoplayEnabled Cookie said No "); setAutoplay(false); return false; } } else { if (typeof autoplay !== 'undefined') { //console.log("isAutoplayEnabled autoplay said " + ((autoplay) ? "Yes" : "No")); setAutoplay(autoplay); return autoplay; } } setAutoplay(false); //console.log("isAutoplayEnabled Default is No "); return false; } function setAutoplay(value) { Cookies.set('autoplay', value, { path: '/', expires: 365 }); } function showAutoPlayVideoDiv() { var auto = $("#autoplay").prop('checked'); if (!auto) { $('#autoPlayVideoDiv').slideUp(); } else { $('#autoPlayVideoDiv').slideDown(); } } function enableAutoPlay() { setAutoplay(true); checkAutoPlay(); } function disableAutoPlay() { setAutoplay(false); checkAutoPlay(); } function checkAutoPlay() { if (isAutoplayEnabled()) { $("#autoplay").prop('checked', true); $('.autoplay-button').addClass('checked'); avideoTooltip(".autoplay-button", "Autoplay is ON"); } else { $("#autoplay").prop('checked', false); $('.autoplay-button').removeClass('checked'); avideoTooltip(".autoplay-button", "Autoplay is OFF"); } showAutoPlayVideoDiv(); } function isPlayNextEnabled() { if (isPlayerLoop()) { return false; } else if (isAutoplayEnabled()) { return true; } return false; } function avideoAlert(title, msg, type) { if (typeof msg == 'undefined') { return false; } if (msg !== msg.replace(/<\/?[^>]+(>|$)/g, "")) {//it has HTML avideoAlertHTMLText(title, msg, type); } else { swal(title, msg, type); } } function _avideoToast(msg, icon) { var options = {text: msg, hideAfter: 7000}; if (icon) { options.icon = icon; } $.toast(options); } function avideoToast(msg) { _avideoToast(msg, null); } function avideoToastInfo(msg) { _avideoToast(msg, 'info'); } function avideoToastError(msg) { _avideoToast(msg, 'error'); } function avideoToastSuccess(msg) { _avideoToast(msg, 'success'); } function avideoToastWarning(msg) { _avideoToast(msg, 'warning'); } function avideoAlertAJAXHTML(url) { modal.showPleaseWait(); $.ajax({ url: url, success: function (response) { avideoAlertText(response); modal.hidePleaseWait(); } }); } function avideoAlertHTMLText(title, msg, type) { var span = document.createElement("span"); span.innerHTML = msg; swal({ title: title, content: span, icon: type, closeModal: true, buttons: type ? true : false, }); } function avideoModalIframe(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe'); } function avideoModalIframeSmall(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe-small'); } function avideoModalIframeLarge(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe-large'); } function avideoModalIframeWithClassName(url, className) { var span = document.createElement("span"); url = addGetParam(url, 'avideoIframe', 1); span.innerHTML = '